package com.gxgeek.userserver.util;



import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2017/8/4.
 */
public class CookieUtil {

    public static void set(HttpServletResponse response, String key,
                           String value, Integer maxAges){
        Cookie cookie = new Cookie(key,value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAges);
        response.addCookie(cookie);
    }
    public static String get(HttpServletRequest request, String key){
        Map<String,Cookie> cookieMap =  readeCookieForMap(request);
        if (cookieMap.containsKey(key)){
            return cookieMap.get(key).getValue();
        }
        return null;
    }

    private static Map<String,Cookie> readeCookieForMap(HttpServletRequest request) {
        if (request.getCookies()!=null){
            return Arrays.stream(request.getCookies()).collect(Collectors.toMap(Cookie::getName, s->s));
        }
        return new HashMap<>();
    }

}
